//
//  STNetworkRequest.m
//  ShaBaoOnline
//
//  Created by huang yong on 16/7/11.
//  Copyright © 2016年 com.ShaBaoOnline.www. All rights reserved.
//

#import "STNetworkRequest.h"

static STNetworkRequest *shareRequest;

@implementation STNetworkRequest

+ (id)shareRequest {
    if(!shareRequest){
        shareRequest = [[STNetworkRequest alloc] init];
    }
    return shareRequest;
}

- (void)startGetRequest:(NSString *)requestUrl parameter:(NSDictionary *)parameter showNetworkErrorAlert:(BOOL)showAlert onCompletion:(RequestCompleteBlock)completionBlock onError:(RequestErrorBlock)errorBlock{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    manager.requestSerializer.timeoutInterval = 30;
    
    NSString *requestString = [NSString stringWithFormat:@"%@%@",baseUrl,requestUrl];
    if (parameter!=nil) {
        requestString = [NSString stringWithFormat:@"%@%@%@",baseUrl,requestUrl,[self filterGetParameterValue:parameter]];
    }
    NSLog(@"requestUrl :%@",requestString);
    
    [manager GET:requestString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        int responseCode = [[responseObject objectForKey:@"result"] intValue];
        if (responseCode == request_success) {
            completionBlock(responseObject);
        }else{
            completionBlock(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //打印输出网络请求失败描述
        if (showAlert) {
            NSLog(@"=========error : %@",error.userInfo.description);
            NSString *erroMsg = [error.userInfo objectForKey:@"NSLocalizedDescription"];
            
        }
        
        errorBlock(error);
    }];
}

- (void)startPostRequest:(NSString *)requestUrl parameter:(NSDictionary *)parameter showNetworkErrorAlert:(BOOL)showAlert  onCompletion:(RequestCompleteBlock)completionBlock onError:(RequestErrorBlock)errorBlock{
    
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    manager.requestSerializer.timeoutInterval = 30;
    NSLog(@"%@",requestUrl);
    [manager POST:requestUrl parameters:parameter success:^(AFHTTPRequestOperation *operation,id responseObject) {
        
        int responseCode = [[responseObject objectForKey:@"result"] intValue];
        
        if (responseCode == request_success) {
            completionBlock(responseObject);
        } else{
            completionBlock(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (showAlert) {
            NSString *erroMsg = [error.userInfo objectForKey:@"NSLocalizedDescription"];
        }
        errorBlock(error);
    }];
    
}

//对GET请求参数进行过滤填充
- (NSString *)filterGetParameterValue:(NSDictionary *)parmeter{
    
    if (parmeter!=nil) {
        NSMutableString *getRequestString = [[NSMutableString alloc] init];
        for (NSString *key in [parmeter allKeys]) {
            NSString *value = [NSString stringWithFormat:@"%@",[parmeter objectForKey:key]];
            if ([getRequestString stringIsEmpty]) {
                [getRequestString appendString:[NSString stringWithFormat:@"?%@=%@",key,value]];
            }else{
                [getRequestString appendString:[NSString stringWithFormat:@"&%@=%@",key,value]];
            }
        }
        NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)getRequestString, NULL, NULL,  kCFStringEncodingUTF8 ));
        return encodedString;
    }
    return nil;
}

//对Post请求参数进行过滤填充
- (NSDictionary *)filterPostParameterValue:(NSDictionary *)parmeter{
    NSMutableDictionary *dit = [[NSMutableDictionary alloc] init];
    if (parmeter!=nil) {
        
        NSArray *keys = [parmeter allKeys];
        for (NSString *key in keys) {
            id value = [parmeter objectForKey:key];
            NSString *keyValue = [NSString stringWithFormat:@"%@",value];
            NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                                            (CFStringRef)keyValue,
                                                                                                            NULL,
                                                                                                            NULL,
                                                                                                            kCFStringEncodingUTF8));
            [dit setValue:encodedString forKey:key];
        }
        return dit;
    }
    return nil;
}

//有图片上传
- (void)startPostUpload:(NSString *)urlstr params:(NSDictionary *)params iconFile:(NSString *)iconName imageFiles:(NSArray *)files onCompletion:(RequestCompleteBlock)completionBlock onError:(RequestErrorBlock)errorBlock{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *upload = [NSString stringWithFormat:@"%@%@",baseUrl,urlstr];
    [manager POST:upload parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if(nil != iconName){
            [formData appendPartWithFileData:[[NSFileManager defaultManager] contentsAtPath:iconName] name:@"icon" fileName:iconName mimeType: [NSString stringWithFormat:@"image/%@",[iconName pathExtension]]];
        }
        
        if(nil != files){
            for(int i = 0; i < files.count; i++)
            {
                NSString * fileName = [files objectAtIndex:i];
                [formData appendPartWithFileData:[[NSFileManager defaultManager] contentsAtPath:fileName] name:@"photo" fileName:fileName mimeType:[NSString stringWithFormat:@"image/%@",[fileName pathExtension]]];
            }
        }
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        int responseCode = [[responseObject objectForKey:@"result"] intValue];
        
        if (responseCode == request_success) {
            completionBlock(responseObject);
        }else {
            completionBlock(responseObject);
        }
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        errorBlock(error);
    }];
}

//无图片上传
- (void)startPostUpload:(NSString *)urlstr params:(NSDictionary *)params onCompletion:(RequestCompleteBlock)completionBlock onError:(RequestErrorBlock)errorBlock{
    [self startPostUpload:urlstr params:params iconFile:nil imageFiles:nil onCompletion:completionBlock onError:errorBlock];
}

@end
